package eightDataType;

/**
 * @author Ajie
 * @date 2022/9/12
 * @function JAVA INTEGER溢出判断的两种方法
 *
 * Math.addExact(x, x); //throw ArithmeticException >>> integer overflow
 */
public class IntDemo_Overflow {
    public static void main(String[] args) {
        int x = Integer.MAX_VALUE;
        int xResult;
        try {
            System.out.println("x =" + x);
            xResult = Math.addExact(x, x); //throw ArithmeticException >>> integer overflow
            System.out.println("x+x = " + xResult);
        } catch (ArithmeticException aex) {
            System.err.println("x + x 溢出," + aex.getMessage());
        }

        //判断int 减法 是否溢出
        x = Integer.MIN_VALUE;
        try {
            System.out.println("x=" + x);
            xResult = Math.subtractExact(x, 1);//throw ArithmeticException >>> integer overflow
            System.out.println("x-x = " + xResult);
        } catch (ArithmeticException aex) {
            System.out.println("x - 1 溢出," + aex.getMessage());
        }
        //判断int 乘法 是否溢出
        x = Integer.MAX_VALUE;
        try {
            System.out.println("x=" + x);
            xResult = Math.multiplyExact(x, x);//throw ArithmeticException >>> integer overflow
            System.out.println("x*x = " + xResult);
        } catch (ArithmeticException aex) {
            System.out.println("x * x 溢出," + aex.getMessage());
        }
    }
}
